<template>

	<el-container>
		<el-aside width="50%">
			<textarea
				style="background-color: #000000;border-radius: 0.625rem;padding: 0.625rem;color: #FFFFFF;margin-left:2rem;"
				:disabled="disabled" cols="120" rows="40" v-model="UnvarnishedList"></textarea>
		</el-aside>
		<el-container>
			<el-main>
				<el-select :placeholder="$t('wel.table.pleaseSelectDevice')" v-model="selectDevice"
					@change="changeDeivce">
					<el-option v-for="item in device" :key="item.id" :label="item.name" :value="item.code">
					</el-option>
				</el-select>
				<el-select style="margin-left: 2rem;" v-model="selectInstructions" @change="changeInstructions">
					<el-option v-for="item in instructions" :key="item.id" :label="item.name" :value="item.name">
					</el-option>
				</el-select>
				<el-input placeholder="sub:" style="width: 70%;margin-top: 2rem;" v-model="sub" disabled></el-input>
				<el-input placeholder="pub:" style="width: 70%;margin-top: 2rem;" v-model="pub" disabled></el-input>
				<textarea style="background-color: #F0F7FF;border-radius: 0.625rem;padding: 0.625rem;margin-top: 2rem;"
					cols="100" rows="20" :placeholder="$t('wel.table.please_enter_tran')" v-model="text"></textarea>

				<el-button type="primary" @click="SendUnvarnished"
					style="margin-top: 0rem;margin-top: 2rem;width: 40%;">
					{{$t('wel.table.send_out')}}
				</el-button>
			</el-main>
			<el-footer>

			</el-footer>
		</el-container>
	</el-container>
</template>

<script>
	import mqtt from 'mqtt'
	import {
		mapGetters
	} from "vuex";
	import request from '@/router/axios';
	import {
		baseUrl,
		MQTT_SERVICE,
		MQTT_USERNAME,
		MQTT_PASSWORD
	} from '@/config/env';
	var client;
	var clientId = Math.floor(Math.random() * (9999999 - 1000000) + 1000000)

	const options = {
		connectTimeout: 40000,
		clientId: "user" + clientId,
		username: MQTT_USERNAME,
		password: MQTT_PASSWORD,
		clean: true
	}
	export default {
		name: "wel",
		data() {
			return {
				userInfo: {},
				disabled: true,
				UnvarnishedList: "",
				Unvarnished: '',
				ws: null,
				device: [],
				selectDevice: "",
				selectInstructions: "",
				sub: "",
				pub: "",
				text: "",
				instructions: [{
						id: 0,
						name: "reload"
					},
					{
						id: 1,
						name: "reboot"
					},
					{
						id: 2,
						name: "reqSysInfo"
					},
					{
						id: 3,
						name: "cfgSysParams"
					}, {
						id: 4,
						name: "getSysParams"
					}, {
						id: 5,
						name: "cfgDOParams"
					},{
						id:6,
						name:"reqDOParams",
					},{
						id:7,
						name:"setDOStatus",
					}


				]
			}
		},
		created() {
			this.getAllDevice();
			this.getUserinfo();
		},
		methods: {
			//发送消息
			SendUnvarnished() {
				console.log(this.sub);
				if (this.sub) {
					client.publish(this.sub, this.text);
					this.UnvarnishedList = this.UnvarnishedList + "↑  "+this.sub+"  \r\n" + this.text + "\r\n\r\n";
				}
			},
			changeInstructions(row) {
				let msgId = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", "").replace(/-/g,
					"").replace(/:/g, "");
				if (row == "reload") {
					this.text = '{"msgId":' + msgId + ',"sn":"' + this.selectDevice + '","method":"reload"}';
				} else if (row == "reboot") {
					this.text = '{"msgId":' + msgId + ',"sn":"' + this.selectDevice + '","method":"reboot"}';
				} else if (row == "reqSysInfo") {
					this.text = '{"msgId":' + msgId + ',"sn":"' + this.selectDevice + '","method":"reqSysInfo"}';
				} else if (row == "cfgSysParams") {
					this.text = '{"msgId":' + msgId + ',"sn":"' + this.selectDevice +
						'","method":"cfgSysParams","params":{"keepAliveTime":0,"data":"10"}}';
				} else if (row == "getSysParams") {
					this.text = '{"msgId":' + msgId + ',"sn":"' + this.selectDevice + '","method":"getSysParams"}';
				} else if (row == "cfgDOParams") {
					this.text = '{"msgId":' + msgId + ',"sn":"' + this.selectDevice + '","method":"cfgDOParams","params":[{"num":0,"mode":0,"isPost":0,"pulseTime":10}]}';
				}else if(row=="reqDOParams"){
					this.text = '{"msgId":' + msgId + ',"sn":"' + this.selectDevice + '","method":"cfgDOParams","params":[{"chTab":[1,2]}]}';
				}else if(row=="setDOStatus"){
					this.text = '{"msgId":' + msgId + ',"sn":"' + this.selectDevice + '","method":"setDOStatus","params":[{"num":1,"value":1}]}';
				}
			},
			changeDeivce(row) {
				console.log(row);
				if (this.pub !== "") {
					client.unsubscribe(this.pub, error => {
						if (error) {
							console.log('Unsubscribe error', error)
						}
					})
				}
				this.sub = "all/" + row + "/sub";
				this.pub = "all/" + row + "/pub";
				client.subscribe(this.pub, {
					qos: 1
				}, (error) => {
					if (!error) {
						console.log('订阅成功')
					} else {
						console.log('订阅失败')
					}
				})
			},
			getAllDevice() {
				let that = this;
				//提交数据
				request({
						headers: {
							"Content-Type": "application/json;charset=utf-8",
						},
						method: "post",
						url: baseUrl + "/api/device/getAllDevice",
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info);
						} else if (response.data.status == 1) {
							that.device = response.data.data;
						}
					})
					.catch(function(error) {
						that.$message.error(that.$t("wel.table.System_error"));
					});
			},

			getUserinfo() {
				let that = this;
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/user/userinfo',
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							that.userInfo = response.data.data;
							// mqtt连接

							that.mqttMSG();
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},

			mqttMSG() {
				let that = this;
				console.log("准备连接MQTT");
				console.log("连接状态：", this.clientStatus);
				if (!this.clientStatus) {
					options.clientId = Math.floor(Math.random() * (9999999 - 1000000) + 1000000)
					client = mqtt.connect(MQTT_SERVICE, options)
				}
				client.on('connect', (e) => {
					this.clientStatus = true;
					console.log('连接成功:', that.device)

				})
				// 接收消息处理
				client.on('message', (topic, message) => {
					var data = JSON.parse(message);
					that.UnvarnishedList = that.UnvarnishedList + "↓  "+topic+"  \r\n" + JSON.stringify(data) + "\r\n\r\n";
				})
				// 断开发起重连
				client.on('reconnect', (error) => {
					console.log('正在重连:', error)
				})
				// 链接异常处理
				client.on('error', (error) => {
					console.log('连接失败:', error)
				})
			},
		}
	};
</script>

<style scoped="scoped" lang="scss">
	.wel {
		&__header {
			padding: 25px 40px;
			border-bottom: 1px solid #e8e8e8;
			background-color: #fff;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		&__info {
			display: flex;
			align-items: center;

			&-img {
				border-radius: 72px;
				display: block;
				width: 72px;
				height: 72px;

				img {
					width: 100%;
					height: 100%;
					display: block;
				}
			}

			&-content {
				position: relative;
				margin-left: 24px;
				color: rgba(0, 0, 0, 0.45);
				line-height: 22px;
			}

			&-title {
				font-size: 20px;
				line-height: 28px;
				font-weight: 500;
				color: rgba(0, 0, 0, 0.85);
				margin-bottom: 12px;
			}

			&-subtitle {
				position: relative;
				font-size: 14px;
				color: rgba(0, 0, 0, 0.45);
				line-height: 22px;
			}
		}

		&__extra {
			&-item {
				position: relative;
				padding: 0 32px;
				display: inline-block;

				&:last-child {
					&::after {
						display: none;
					}
				}

				&:after {
					background-color: #e8e8e8;
					position: absolute;
					top: 30px;
					right: 0;
					width: 1px;
					height: 40px;
					content: "";
				}
			}

			&-title {
				color: rgba(0, 0, 0, 0.45);
				font-size: 14px;
				line-height: 22px;
				margin-bottom: 4px;
			}

			&-subtitle {
				color: rgba(0, 0, 0, 0.85);
				font-size: 30px;
				line-height: 38px;
				margin: 0;

				span {
					color: rgba(0, 0, 0, 0.45);
					font-size: 20px;
				}
			}
		}
	}
</style>
